package com.jubaopen.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class DomainFilter implements Filter {

	private static final String DOMAIN = "39249.com";
	private static final String URL_SEP = "/";
	@Override
	public void init(FilterConfig filterconfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request; 
		String domainName = "";
		
		String serverName = req.getServerName();
		
		String path = req.getRequestURI();
		
		int end = serverName.indexOf(DOMAIN);
		
		if (end != -1 && end != 0) {
			domainName = serverName.substring(0,end - 1);
		}else {
			domainName = "www";
		}
		
		String distPage = getDistPage(path);
		
		if (domainName != null && !"".equals(domainName) && !"www".equals(domainName)) {
			 //&& !distPage.contains(".") 
			if (domainName.equals("me")) {
				req.getRequestDispatcher(URL_SEP+domainName+URL_SEP+distPage)
					.forward(request, response);
			}else {
				req.getRequestDispatcher(URL_SEP+"me"+URL_SEP+domainName)
				.forward(request, response);
			}
			
			return;
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}
	
	private static String getDistPage(String path) {
        if (path == null && "".equals(path)) {
            return null;
        }

        String args[] = path.split("/");
        if (args.length < 2) {
            return null;
        }

        return args[1];
    }
	
	/*
	private static String getId(String path) {
        if (path == null && "".equals(path)) {
            return null;
        }
        String args[] = path.split("/");
        if (args.length < 3) {
            return null;
        }

        return args[2];
    }
	*/

}
